package com.leemon.mall.sys.controller;


import com.leemon.mall.security.dto.MySysUser;
import com.leemon.mall.security.util.SecurityUtils;
import com.leemon.mall.sys.dto.UpdatePassowrdDto;
import com.leemon.mall.sys.model.SysUser;
import com.leemon.mall.sys.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.validation.Valid;

/**
 * <p>
 * 系统用户 前端控制器
 * </p>
 *
 * @author leemon
 * @since 2019-09-04
 */
@Api(tags = "后台-用户接口", description = "SysUserController")
@RestController
@RequestMapping("/sys/user")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @ApiOperation("获取登陆的用户信息")
    @GetMapping("/info")
    public ResponseEntity info() {
        SysUser sysUser = sysUserService.getByUserId(SecurityUtils.getSysUser().getUserId());
        return ResponseEntity.ok(sysUser);
    }


    @PostMapping("/password")
    @ApiOperation("修改当前登录用户的密码")
    //自定义判断权限的方法
    @PreAuthorize("@permission.hasPermission('sys:user:update')")
    //默认的判断权限的方法
//    @PreAuthorize("hasAuthority('sys:user:update')")
    public ResponseEntity password(@RequestBody @Valid UpdatePassowrdDto updatePassowrdDto) {

        Long userId = SecurityUtils.getSysUser().getUserId();
        SysUser dbSysUser = sysUserService.getByUserId(userId);
        if (!passwordEncoder.matches(updatePassowrdDto.getPassword(), dbSysUser.getPassword())) {
            return ResponseEntity.badRequest().body("原密码不正确");
        }

        //新密码
        String password = passwordEncoder.encode(updatePassowrdDto.getNewPassword());
        sysUserService.updatePasswordByUserId(userId, password);
        return ResponseEntity.ok().build();

    }
}

